package com.nuaa.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuaa.model.cmn.Dict;
import com.nuaa.vo.cmn.DictEeVo;
import com.nuaa.yygh.cmn.listener.DictListener;
import com.nuaa.yygh.cmn.mapper.DictMapper;
import com.nuaa.yygh.cmn.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper,Dict> implements DictService {


    //实现上传方法
    //在数据上传之后，数据库内容发生改变，自然要相应的清空缓存
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void improtData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //通过父类code和value查询
    @Override
    public String getNameByDictCodeAndValue(String dictCode, String value) {
        //value若可以唯一确定数据字典，父类code可以传空。省市区的value唯一确定
        //dictcode为空
        if(StringUtils.isEmpty(dictCode)){
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else{
            //不空
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_code",dictCode);
            Dict dict_code = baseMapper.selectOne(wrapper);
            //再去获取dict对象的父类id值
            Long parent_id = dict_code.getId();
            //
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value));
            return dict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //先根据dictcode得到对象
        Dict dict = this.getDictByDictCode(dictCode);
        if(null == dict) return null;
        //再用对象得到id
        return this.findChildData(dict.getId());
    }
    //根据dictcode得到对象
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;
    }

    //根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        //eq就是找到这个id字段 = “parent_id"的id
        wrapper.eq("parent_id",id);
        //创建集合来存wrapper对象
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //需要向list中的每个元素设置hasChildren属性
        for (Dict dict: dictList){
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }


    //实现下载方法
    @Override
    public void exportData(HttpServletResponse response) {
        //导出过程就是下载过程
        //设置下载的相关信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName ="dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        //给将Dict类型转成DictEeVo类型

        List<DictEeVo> dictVoList = new ArrayList<>();
        for(Dict dict : dictList) {
            DictEeVo dictVo = new DictEeVo();
            //复制dict
            BeanUtils.copyProperties(dict,dictVo);
            dictVoList.add(dictVo);
        }

        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    //先判断id下面是否有子节点
    private boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
